// 日期格式化
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time)
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/')
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}
export function replaceStr(start, end, str) {
    const newArr = [...str]
    if (str.length >= end) {
        for (let a = 0; a < end; a++) {
            if (a >= start) {
                newArr[a] = newArr[a].replace(newArr[a], '*')
            }
        }
        return newArr.join('')
    } else {
        return '未知'
    }
}
export function checkMobile(mobile) {
    return RegExp(/^1[23456789]\d{9}$/).test(mobile)
}

export function getAgoDay(n) {
    const date = new Date()
    const newDate = new Date(date.getTime() - n * 24 * 60 * 60 * 1000)
    return parseTime(newDate, '{y}-{m}-{d}')
}
export function getDay(num) {
    const d = new Date()
    let year = d.getFullYear()
    let mon = d.getMonth() + 1
    let day = d.getDate()
    if (day <= num) {
        if (mon > 1) {
            mon = mon - 1
        } else {
            year = year - 1
            mon = 12
        }
    }
    d.setDate(d.getDate() - num)
    year = d.getFullYear()
    mon = d.getMonth() + 1
    day = d.getDate()
    const s = year + '-' + (mon < 10 ? '0' + mon : mon) + '-' + (day < 10 ? '0' + day : day)
    return s
}
// 获取日期范围内日期
export function getDayPro(dayType) {
    console.log(parseTime, 'parseTime')
    return new Promise(function (resolve, reject) {
        const today = new Date()
        let currentDate = ''
        if (dayType === '本周') {
            // 获取当前日期
            // 获取今天是星期几（0 表示星期日，1 表示星期一，以此类推）
            var dayOfWeek = today.getDay()
            // 计算星期一距离今天的天数
            const daysUntilMonday = 1 - dayOfWeek

            // 计算星期一的日期
            const monday = new Date(today)
            monday.setDate(today.getDate() + daysUntilMonday)
            console.log('本周星期一的日期是：' + parseTime(monday.toDateString(), '{y}-{m}-{d}'))
            currentDate = `${parseTime(monday.toDateString(), '{y}-{m}-{d}')}至${parseTime(new Date(), '{y}-{m}-{d}')}`
        }
        if (dayType === '本月') {
            // 获取当前月份的第一天
            const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
            // 输出本月第一天的日期
            currentDate = `${parseTime(firstDayOfMonth.toDateString(), '{y}-{m}-{d}')}至${parseTime(new Date(), '{y}-{m}-{d}')}`
        }
        if (dayType === '上周') {
            // 获取今天是星期几（0 表示星期日，1 表示星期一，以此类推）
            var dayOfWeek = today.getDay()
            // 计算上周星期一距离今天的天数
            const daysUntilLastMonday = dayOfWeek + 6 // 加 6 天是因为今天也算一天
            // 计算上周星期一的日期
            const lastMonday = new Date(today)
            lastMonday.setDate(today.getDate() - daysUntilLastMonday)

            // 获取今天是星期几（0 表示星期日，1 表示星期一，以此类推）
            const dayOfWeek1 = today.getDay()

            // 计算上周星期日距离今天的天数
            const daysUntilLastSunday = dayOfWeek1
            // 计算上周星期日的日期
            const lastSunday = new Date(today)
            lastSunday.setDate(today.getDate() - daysUntilLastSunday)

            // 调整日期到上周
            lastSunday.setDate(lastSunday.getDate())

            // 输出上周星期一的日期
            console.log('上周星期一的日期是：' + parseTime(lastMonday.toDateString()))
            // 输出上周星期日的日期
            console.log('上周星期日的日期是：' + parseTime(lastSunday.toDateString()))
            currentDate = `${parseTime(lastMonday.toDateString(), '{y}-{m}-{d}')}至${parseTime(lastSunday.toDateString(), '{y}-{m}-{d}')}`
        }
        if (dayType === '上月') {
            // 获取上个月的年份和月份
            let lastMonthYear = today.getFullYear()
            let lastMonth = today.getMonth() - 1

            // 如果当前月份是一月，需要减少年份，并设置月份为十二月
            if (lastMonth < 0) {
                lastMonthYear -= 1
                lastMonth = 11 // JavaScript 月份是从0开始，十二月是11
            }

            // 获取上个月的第一天（1号）
            const firstDayOfLastMonth = new Date(lastMonthYear, lastMonth, 1)

            // 获取本月的第一天（1号）
            const firstDayOfThisMonth = new Date(today.getFullYear(), today.getMonth(), 1)

            // 获取上个月的最后一天（这个月的0号，即上个月的最后一天）
            const lastDayOfLastMonth = new Date(firstDayOfThisMonth)
            lastDayOfLastMonth.setDate(0)
            console.log('上个月的1号是：' + parseTime(firstDayOfLastMonth.toDateString()))
            console.log('上个月的最后一天是：' + parseTime(lastDayOfLastMonth.toDateString()))
            currentDate = `${parseTime(firstDayOfLastMonth.toDateString(), '{y}-{m}-{d}')}至${parseTime(
                lastDayOfLastMonth.toDateString(),
                '{y}-{m}-{d}'
            )}`
        }
        resolve(currentDate)
    })
}
export function dateScope(DateOne, DateTwo) {
    const OneMonth = DateOne.substring(5, DateOne.lastIndexOf('-'))

    const OneDay = DateOne.substring(DateOne.length, DateOne.lastIndexOf('-') + 1)

    const OneYear = DateOne.substring(0, DateOne.indexOf('-'))

    const TwoMonth = DateTwo.substring(5, DateTwo.lastIndexOf('-'))

    const TwoDay = DateTwo.substring(DateTwo.length, DateTwo.lastIndexOf('-') + 1)

    const TwoYear = DateTwo.substring(0, DateTwo.indexOf('-'))

    const cha = (Date.parse(OneMonth + '/' + OneDay + '/' + OneYear) - Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear)) / 86400000

    return Math.abs(cha) + 1 //因为减出来的时间会少一天，所以我们需要+1
}
//  是否为微信内置浏览器
export function isWeixinBrowser() {
    const ua = navigator.userAgent.toLowerCase()
    return /micromessenger/.test(ua) ? true : false
}
export function judgeClient() {
    const u = navigator.userAgent

    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //判断是否是 android终端

    const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //判断是否是 iOS终端

    if (isAndroid) {
        return 'Android'
    } else if (isIOS) {
        return 'IOS'
    } else {
        return 'PC'
    }
}
